﻿using CodeGenerator.Common;
using CodeGenerator.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CodeGenerator.UI
{
    public partial class FrmCreateEntityMulti : Form
    {
        public FrmCreateEntityMulti()
        {
            InitializeComponent();
        
        }

        private List<TableInfo> selectTable = null;
        private string outputDir = string.Empty;
        private string prefix = string.Empty;
        private CodeType codeType = CodeType.NET;
        private string templetePath = "\\Template\\Entity\\SimpleEntity.cshtml";

        private BackgroundWorker doWork = null;

        private void FrmCreateEntityMulti_Load(object sender, EventArgs e)
        {
            progressBar1.Visible = false;
            MainSetting info = Config.GetSetupInfo();

            txtPrefix.Text = info.Prefix;
            txtOutputDir.Text = info.OutputDir;
        }

        private void btnChoose_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            folderBrowserDialog.ShowDialog();
            txtOutputDir.Text = folderBrowserDialog.SelectedPath;
        }

        private void FrmCreateEntityMulti_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (doWork != null && doWork.IsBusy)
            {
                Common.MessageUtil.ShowWarning("任务执行中，无法关闭！！！");
                e.Cancel = true;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        } 

        private void btnOk_Click(object sender, EventArgs e)
        {
            selectTable = ucSelectTable1.GetSelectTable;

            if (selectTable.Count > 0)
            {
                prefix = txtPrefix.Text.Trim();
                outputDir = txtOutputDir.Text.Trim();

                if (string.IsNullOrEmpty(outputDir))
                {
                    Common.MessageUtil.ShowWarning("请选择输出路径！！！");
                    return;
                }
               
                if (radioButton1.Checked)
                {
                    codeType = CodeType.NET;
                }
                else if (radioButton2.Checked)
                {
                    codeType = CodeType.NET;
                    templetePath = "\\Template\\Entity\\ComplexEntity.cshtml";
                }
                else if (radioButton3.Checked)
                {
                    codeType = CodeType.Java;
                    templetePath = "\\Template\\Entity\\JavaEntity.cshtml";
                }

                progressBar1.Visible = true;
                progressBar1.Minimum = 0;
                progressBar1.Maximum = selectTable.Count + 2;
                doWork = new BackgroundWorker();
                doWork.DoWork += doWork_DoWork;
                doWork.ProgressChanged += doWork_ProgressChanged;
                doWork.RunWorkerCompleted += doWork_RunWorkerCompleted;
                doWork.WorkerReportsProgress = true;//此属性必须设置，否则读取不到进度
                doWork.WorkerSupportsCancellation = true; // 运行取消操作
                doWork.RunWorkerAsync();
            }
            else
            {
                Common.MessageUtil.ShowWarning("请至少选择一个表！！！");
            }
        }

        void doWork_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //如果用户取消了当前操作就关闭窗口。
            if (e.Cancelled)
            {
                this.lblMsg.Text = "用户取消操作！！！";
            }
            else
            {
                this.lblMsg.Text = "执行完成！！！";
                doWork.CancelAsync();
                this.Close();
            }

        }

        void doWork_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            //修改进度条的显示。
            this.progressBar1.Value = e.ProgressPercentage;

            string message = e.UserState.ToString();
            this.lblMsg.Text = message;
        }

        void doWork_DoWork(object sender, DoWorkEventArgs e)
        {
            //在操作的过程中需要检查用户是否取消了当前的操作。
            if (doWork.CancellationPending == true)
            {
                e.Cancel = true;
                return;
            }
           

            BackgroundWorker bgWorker = sender as BackgroundWorker;

            ServerInfo serverInfo = Constant.CurrentServerInfo;
            serverInfo.DatabaseName = Constant.DatabaseName;
            IDatabase database = DBFactory.Database(serverInfo.DBType);

            string dirPath = outputDir + "\\Entity\\";
         
            string entityPath = string.Empty;

            int i = 0;
            foreach (var table in selectTable)
            {
                i++;
                bgWorker.ReportProgress(i, "正在生成生成【"+table.Name+"】实体...");

                EntityCodeCreate model = GetEntityModel(codeType,table.Name);
                string content = RazorHelper.RunCompile(templetePath, model);

               
                if(codeType== CodeType.NET)
                {
                     entityPath = dirPath + "\\" + table.FilterName(prefix) + "Entity.cs";
                }
                else if (codeType == CodeType.Java)
                {
                    entityPath = dirPath + "\\" + table.FilterName(prefix) + ".java";
                }
                DirectoryUtil.Write(entityPath, content);
            }
            System.Diagnostics.Process.Start(dirPath);
        }


        /// <summary>
        /// 获取生成实体代码对象
        /// </summary>
        /// <param name="codeType"></param>
        /// <returns></returns>
        private EntityCodeCreate GetEntityModel(CodeType codeType,string tableName)
        {
            EntityCodeCreate model = new EntityCodeCreate();
            TableInfo tableInfo = new TableInfo();

            ServerInfo server = Constant.CurrentServerInfo;
            IDatabase database = DBFactory.Database(server.DBType);

            tableInfo.Name = tableName;
            tableInfo.Comments = database.GetTableComments(server,Constant.DatabaseName, tableName);
            tableInfo.ColumnList = database.GetColumnInfoList(server, server.DatabaseName, tableName);
            model.TableInfo = tableInfo;

            model.Name = tableName;

            MainSetting info = Config.GetSetupInfo();

            string[] prefixs = info.Prefix.Split(',');
            foreach (var prefix in prefixs)
            {
                if (!string.IsNullOrEmpty(prefix) && model.Name.Contains(prefix))
                {
                    model.Name = model.TableInfo.Name.Replace(prefix, "");
                    break;
                }
            }

            if (codeType == CodeType.NET)
            {
                model.NameSpace = info.NameSpace;
            }
            else if (codeType == CodeType.Java)
            {
                model.NameSpace = info.EntityPackage;
            }

            return model;
        }
        
        
    }
}
